package com.liang.bishi.nj;

/**
 * 第二题：Java多线程交替打印奇数和偶数
 * 2.1 使用 synchronized
 */
public class Problem02_1 {
    private final int maxCount; // 最大数字
    private int current = 1;
    private final Object lock = new Object();

    public Problem02_1(int maxCount) {
        this.maxCount = maxCount;
    }

    // 开启两个线程分别打印奇数和偶数
    public void start() throws InterruptedException {
        // 线程 OddThread 调用 printOdd();
        Thread oddThread = new Thread(() -> {
            while (current < maxCount) {
                synchronized (lock) {
                    if (current % 2 != 0 && current <= maxCount) {
                        System.out.println(Thread.currentThread().getName() + ":" + current++);
                    }
                }
            }
        }, "OddThread");

        // 线程 EvenThread 调用 printEven();
        Thread evenThread = new Thread(() -> {
            while (current < maxCount) {
                synchronized (lock) {
                    if (current % 2 == 0 && current <= maxCount) {
                        System.out.println(Thread.currentThread().getName() + ":" + current++);
                    }
                }
            }
        }, "EvenThread");

        // 启动两个线程
        oddThread.start();
        evenThread.start();

        // 等待子线程执行完成
        oddThread.join();
        evenThread.join();
    }

    public static void main(String[] args) throws InterruptedException {
        Problem02_1 test02 = new Problem02_1(100);
        test02.start();
    }
}
